package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.HomeworkSubmitDTO;
import com.cyzy.homework.service.HomeworkSubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 作业提交控制器
 */
@RestController
@RequestMapping("/api/homework-submit")
@CrossOrigin(origins = "*")
public class HomeworkSubmitController {
    
    @Autowired
    private HomeworkSubmitService homeworkSubmitService;
    
    /**
     * 提交作业
     */
    @PostMapping
    public Result<HomeworkSubmitDTO> submitHomework(
            @RequestParam Long homeworkId,
            @RequestParam String userId,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) List<MultipartFile> files) {
        try {
            HomeworkSubmitDTO result = homeworkSubmitService.submitHomework(homeworkId, userId, content, files);
            return Result.success("作业提交成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新作业提交
     */
    @PutMapping("/{id}")
    public Result<HomeworkSubmitDTO> updateSubmit(
            @PathVariable Long id,
            @RequestParam String userId,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) List<MultipartFile> files) {
        try {
            HomeworkSubmitDTO result = homeworkSubmitService.updateSubmit(id, userId, content, files);
            return Result.success("作业提交更新成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除作业提交
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteSubmit(@PathVariable Long id, 
                                   @RequestParam String userId) {
        try {
            homeworkSubmitService.deleteSubmit(id, userId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID查询作业提交
     */
    @GetMapping("/{id}")
    public Result<HomeworkSubmitDTO> getSubmitById(@PathVariable Long id) {
        try {
            HomeworkSubmitDTO result = homeworkSubmitService.getSubmitById(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据作业ID和学生ID查询提交记录
     */
    @GetMapping("/homework/{homeworkId}/user/{userId}")
    public Result<HomeworkSubmitDTO> getSubmitByHomeworkIdAndUserId(
            @PathVariable Long homeworkId,
            @PathVariable String userId) {
        try {
            HomeworkSubmitDTO result = homeworkSubmitService.getSubmitByHomeworkIdAndUserId(homeworkId, userId);
            if (result == null) {
                return Result.notFound("未找到提交记录");
            }
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据作业ID查询提交列表
     */
    @GetMapping("/homework/{homeworkId}")
    public Result<Page<HomeworkSubmitDTO>> getSubmitsByHomeworkId(
            @PathVariable Long homeworkId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "submitTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkSubmitDTO> result = homeworkSubmitService.getSubmitsByHomeworkId(homeworkId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据学生ID查询提交列表
     */
    @GetMapping("/user/{userId}")
    public Result<Page<HomeworkSubmitDTO>> getSubmitsByUserId(
            @PathVariable String userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "submitTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkSubmitDTO> result = homeworkSubmitService.getSubmitsByUserId(userId, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据作业ID和状态查询提交列表
     */
    @GetMapping("/homework/{homeworkId}/status/{status}")
    public Result<Page<HomeworkSubmitDTO>> getSubmitsByHomeworkIdAndStatus(
            @PathVariable Long homeworkId,
            @PathVariable Integer status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "submitTime") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort sort = sortDir.equalsIgnoreCase("desc") ? 
                Sort.by(sortBy).descending() : Sort.by(sortBy).ascending();
            Pageable pageable = PageRequest.of(page, size, sort);
            
            Page<HomeworkSubmitDTO> result = homeworkSubmitService.getSubmitsByHomeworkIdAndStatus(homeworkId, status, pageable);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批改作业
     */
    @PostMapping("/{id}/grade")
    public Result<HomeworkSubmitDTO> gradeHomework(
            @PathVariable Long id,
            @RequestParam String graderId,
            @RequestParam Integer score,
            @RequestParam(required = false) String comment) {
        try {
            HomeworkSubmitDTO result = homeworkSubmitService.gradeHomework(id, graderId, score, comment);
            return Result.success("作业批改成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批量批改作业
     */
    @PostMapping("/batch-grade")
    public Result<List<HomeworkSubmitDTO>> batchGradeHomework(
            @RequestParam List<Long> ids,
            @RequestParam String graderId,
            @RequestParam Integer score,
            @RequestParam(required = false) String comment) {
        try {
            List<HomeworkSubmitDTO> result = homeworkSubmitService.batchGradeHomework(ids, graderId, score, comment);
            return Result.success("批量批改成功", result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 查询未批改的提交
     */
    @GetMapping("/homework/{homeworkId}/ungraded")
    public Result<List<HomeworkSubmitDTO>> getUnGradedSubmits(@PathVariable Long homeworkId) {
        try {
            List<HomeworkSubmitDTO> result = homeworkSubmitService.getUnGradedSubmits(homeworkId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 查询已批改的提交
     */
    @GetMapping("/homework/{homeworkId}/graded")
    public Result<List<HomeworkSubmitDTO>> getGradedSubmits(@PathVariable Long homeworkId) {
        try {
            List<HomeworkSubmitDTO> result = homeworkSubmitService.getGradedSubmits(homeworkId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 检查学生是否已提交作业
     */
    @GetMapping("/homework/{homeworkId}/user/{userId}/check")
    public Result<Boolean> hasStudentSubmitted(
            @PathVariable Long homeworkId,
            @PathVariable String userId) {
        try {
            boolean result = homeworkSubmitService.hasStudentSubmitted(homeworkId, userId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取学生作业提交统计
     */
    @GetMapping("/user/{userId}/statistics")
    public Result<Object> getStudentSubmitStatistics(@PathVariable String userId) {
        try {
            Object result = homeworkSubmitService.getStudentSubmitStatistics(userId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取作业提交统计
     */
    @GetMapping("/homework/{homeworkId}/statistics")
    public Result<Object> getHomeworkSubmitStatistics(@PathVariable Long homeworkId) {
        try {
            Object result = homeworkSubmitService.getHomeworkSubmitStatistics(homeworkId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
